package com.qkm.xinguan.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qkm.xinguan.constant.SystemConst;
import com.qkm.xinguan.domain.entity.HouseInfo;
import com.qkm.xinguan.domain.entity.Notice;
import com.qkm.xinguan.domain.entity.User;
import com.qkm.xinguan.domain.infrastructure.security.LoginUser;
import com.qkm.xinguan.domain.infrastructure.utils.SpringComponentUtil;
import com.qkm.xinguan.domain.infrastructure.utils.UserUtil;
import com.qkm.xinguan.domain.transform.dto.HouseInfoDTO;
import com.qkm.xinguan.domain.transform.dto.UserDTO;
import com.qkm.xinguan.domain.transform.error.HouseErrorInfo;
import com.qkm.xinguan.domain.transform.form.HouseInfoSearchForm;
import com.qkm.xinguan.exception.BindingResultException;
import com.qkm.xinguan.exception.BusinessException;
import com.qkm.xinguan.oss.OssEntity;
import com.qkm.xinguan.repository.HouseInfoRepository;
import com.qkm.xinguan.repository.OssRepository;
import com.qkm.xinguan.repository.impl.HouseInfoESService;
import com.qkm.xinguan.response.Result;
import com.qkm.xinguan.response.ResultCode;
import com.qkm.xinguan.vo.HouseInfoVo;
import com.qkm.xinguan.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author zfj
 * @date 2021/12/1 -15:29
 */
@RestController
public class HouseInfoController implements IHouseInfoController {

	private final HouseInfoRepository houseInfoRepository;

	private final OssRepository ossRepository;

	private final OssEntity ossEntity;

	private final HouseInfoESService houseInfoEsService;

	@Autowired
	public HouseInfoController(HouseInfoRepository houseInfoRepository, OssRepository ossRepository, OssEntity ossEntity,HouseInfoESService houseInfoEsService) {
		this.houseInfoRepository = houseInfoRepository;
		this.ossRepository = ossRepository;
		this.ossEntity = ossEntity;
		this.houseInfoEsService=houseInfoEsService;
	}


	@Override
	public Result getAllListPage(Integer page, Integer size) {
		Page<HouseInfoVo> pageInfo = houseInfoRepository.getHouseInfoListPage(page, size);
		return Result.ok().data(pageInfo);
	}

	@Override
	public Result getHouseInfoListPage(Integer page, Integer size) {
		Page<HouseInfoVo> pageInfo = houseInfoRepository.getHouseInfoListPage(page, size);
		return Result.ok().data(pageInfo);
	}

	@Override
	public Result searchHouseInfoListPage(HouseInfoSearchForm houseInfoSearchForm, Integer page, Integer size) {
		Page<HouseInfoVo> pageInfo = houseInfoRepository.searchHouseInfoListPage(houseInfoSearchForm,page, size);
		return Result.ok().data(pageInfo);
	}

	@Override
	public Result addHouseInfo(HouseInfoDTO houseInfoDTO, BindingResult result) throws IOException {
		if (result.hasErrors()) {
			throw new BindingResultException(result);
		}
		LoginUser loginUser = UserUtil.getCurrentLoginUser();
		assert loginUser != null;
		houseInfoDTO.setUserId(loginUser.getId());
		houseInfoDTO.setPhoneNumber(loginUser.getPhoneNumber());
		houseInfoEsService.addES(houseInfoDTO);
		boolean b = houseInfoRepository.save(executeEntity(houseInfoDTO, null));
		if (b) {
			return Result.ok().message("房屋信息添加成功");
		} else {
			throw new BusinessException(ResultCode.ADD_HOUSEINFO.getCode(), "添加房屋信息失败");
		}
	}

	@Override
	public Result deleteHouseInfo(Long id) {
		HouseInfo houseInfo = houseInfoRepository.getById(id);
		if (Objects.isNull(houseInfo)){
			throw new BusinessException(ResultCode.HOUSEINFO_ACCOUNT_NOT_EXIST);
		}
		boolean res = houseInfoRepository.removeById(id);
		if (res) {
			if (!StringUtils.isEmpty(houseInfo.getAvatar())){
				String fileName = houseInfo.getAvatar().replaceFirst(ossEntity.getUrlPrefix(), "");
				ossRepository.deleteFile(fileName);
			}
			return Result.ok().message("删除房屋信息成功");
		}
		throw new BusinessException("删除房屋信息失败");
	}
	@Override
	public Result getOnlyById(Long id) {
		HouseInfo houseInfo = houseInfoRepository.getOnlyById(id);
		if (null != houseInfo) {
			return Result.ok().data(houseInfo);
		} else {
			throw new BusinessException(ResultCode.HOUSEINFO_ACCOUNT_NOT_EXIST);
		}
	}

	@Override
	public Result getOneById(Long id) {
		HouseInfo houseInfo = houseInfoRepository.getById(id);
		if (null != houseInfo) {
			return Result.ok().data(houseInfo);
		} else {
			throw new BusinessException(ResultCode.HOUSEINFO_ACCOUNT_NOT_EXIST);
		}
	}

	@Override
	public Result editHouseInfo(HouseInfoDTO houseInfoDTO, Long id, BindingResult result) throws IOException {
		if (result.hasErrors()) {
			throw new BindingResultException(result);
		}
		return houseInfoRepository.update(id,houseInfoDTO);
	}

	@Override
	public Result updateHouseInfoStatusToPassById(Long id) {
		HouseInfo houseInfo = houseInfoRepository.getById(id);
		int res = houseInfoRepository.updateHouseInfoStatusToPassById(id);
		if(houseInfo.getVerifyState()==0){
			if (res == 1) {
				return Result.ok().message("审核通过");
			}
		} else {
			throw new BusinessException("不能修改状态不是未审核的房屋信息");
		}
		throw new BusinessException(ResultCode.HOUSEINFO_EXAMINE_SUCCESS.getCode(), "房屋审核通过修改失败");
	}

	@Override
	public Result updateHouseInfoStatusToFailById(HouseErrorInfo errorInfo,Long id, BindingResult result) throws IOException {
		if (result.hasErrors()) {
			throw new BindingResultException(result);
		}
		HouseInfo houseInfo = houseInfoRepository.getById(id);
		houseInfoEsService.Fail(id);
		int res = houseInfoRepository.updateHouseInfoStatusToFailById(id,errorInfo);
		if(houseInfo.getVerifyState()==2){
			if (res == 1) {
				return Result.ok().message("审核不通过");
			}
		} else {
			throw new BusinessException("不能修改状态不是未审核的房屋信息");
		}
		throw new BusinessException(ResultCode.HOUSEINFO_EXAMINE_FAIL.getCode(), "房屋审核不通过修改失败");
	}

	@Override
	public Result leaseHouseInfoById(Long id) throws IOException {
		houseInfoEsService.Lease(id);
		int res= houseInfoRepository.leaseHouseInfoById(id);
		if(res>0){
			return Result.ok().message("出租成功");
		}
		throw new BusinessException(ResultCode.HOUSEINFO_EXAMINE_FAIL.getCode(), "出租失败");
	}

	@Override
	public Result selectHouseInfoByUserId(Integer page, Integer size) {
		Page<HouseInfo> houseInfoPage=new Page<>(page,size);
		houseInfoRepository.selectHouseInfoByUserId(houseInfoPage);
		//查询结束之后，Page对象就存在数据了，此时可以
		//通过该Page对象获取对应的行记录和总记录数
		List<HouseInfo> rows = houseInfoPage.getRecords();
		long total = houseInfoPage.getTotal();
		//统一返回结果
		return Result.ok().data(houseInfoPage);
	}
	@Override
	public Result searchPage(String keyword) throws IOException {
		return houseInfoEsService.searchPage(keyword);
	}

	@Override
	public Result searchHouse(String keyword) throws IOException {
		return houseInfoEsService.searchHouse(keyword);
	}

	@Override
	public Result searchDecorate(String keyword) throws IOException {
		return houseInfoEsService.searchDecorate(keyword);
	}

	@Override
	public Result randomFour() {
		List<HouseInfo> houseInfos = houseInfoRepository.randomFour();
		return Result.ok().data(houseInfos);
	}


	/**
	 * 构建实体类对象
	 *
	 * @param houseInfoDTO 传输对象
	 * @return HouseInfo
	 */
	public static HouseInfo executeEntity(HouseInfoDTO houseInfoDTO, Long id) {
		HouseInfo houseInfo = new HouseInfo();
		BeanUtils.copyProperties(houseInfoDTO, houseInfo);
		houseInfo.setId(id);
		return houseInfo;
	}
}
